/*
 * @Author: hongbin
 * @Date: 2023-03-31 22:14:03
 * @LastEditors: hongbin
 * @LastEditTime: 2023-04-01 21:02:26
 * @Description:灵活的八叉树
 */
import { ThreeHelper } from "@/src/ThreeHelper";
import { Octree, getMeshTriangles } from "@/src/ThreeHelper/expand/Octree";
import Layout from "@/src/components/Three/Layout";
import { FC } from "react";
import * as THREE from "three";
import { OctreeHelper } from "three/examples/jsm/helpers/OctreeHelper";
import { Capsule } from "three/examples/jsm/math/Capsule";

interface IProps {}

const Index: FC<IProps> = () => {
    return <Layout title={"THREE TEMPLATE"} init={init} desc="客户端渲染" />;
};

export default Index;

function init(helper: ThreeHelper) {
    helper.addStats();
    helper.addAxis();
    helper.camera.position.set(0, 5, 6);
    helper.frameByFrame();
    helper.addGUI();
    helper.initLights();

    const group = new THREE.Group();

    const box = helper.generateRect(
        {
            width: 0.4,
            height: 0.4,
            depth: 0.4,
        },
        {
            color: new THREE.Color("#faa"),
        }
    );

    for (let i = 0; i < 10; i++) {
        box.name = `box${i}`;
        const boxIns = box.clone();
        boxIns.position.set(i, i, i);
        group.add(boxIns);
    }

    const octree = new Octree();

    octree.fromGraphNode(group);

    box.material = new THREE.MeshPhysicalMaterial({
        color: new THREE.Color("#e10909"),
    });

    const { triangles: boxTriangles, translate } = getMeshTriangles(box);

    const cap = new Capsule();
    cap.radius = 0.2;
    cap.start.set(0, 0.1, 0);
    cap.end.set(0, 0.3, 0);

    // const octreeHelper = new OctreeHelper(
    //     octree as any,
    //     new THREE.Color("#51f")
    // );

    // helper.add(octreeHelper);

    helper.add(group);
    helper.add(box);

    console.log(octree.capsuleIntersect(cap, boxTriangles));
    const consoles = {
        compute: () => {
            console.log(octree.capsuleIntersect(cap, boxTriangles));
        },
        x: 0,
        y: 0,
        z: 0,
    };

    helper.gui?.add(consoles, "compute");
    helper.gui?.add(consoles, "x").onChange((val) => {
        box.position.x = val;
        translate({ x: val, y: 0, z: 0 } as Vector3);
        // cap.start.x = val;
        // cap.end.x = val;
    });
    helper.gui?.add(consoles, "y").onChange((val) => {
        box.position.y = val;
        translate({ x: 0, y: val, z: 0 } as Vector3);
        // cap.start.y = val;
        // cap.end.y = val;
    });
    helper.gui?.add(consoles, "z").onChange((val) => {
        box.position.z = val;
        translate({ x: 0, y: 0, z: val } as Vector3);
        // cap.start.z = val;
        // cap.end.z = val;
    });
}
